//
//  HXImageDownloader.m
//  HXJBP
//
//  Created by zhangjingle on 13-12-18.
//  Copyright (c) 2013年 zhang jingle. All rights reserved.
//

#import "HXImageDownloader.h"

#define IMAGE_DOWNLOADER_URL_STRING @"urlString"
#define IMAGE_DOWNLOADER_USERINFO @"userInfo"
@implementation HXImageDownloader
-(void)dealloc
{
    
    _delegate = nil;
    for (int i = 0; i<[_httpRequestArray count]; i++) {
        ASIHTTPRequest * request = [_httpRequestArray objectAtIndex:i];
        [request clearDelegatesAndCancel];
    }
//    [_httpRequestArray release];
    RELEASE_SAFELY(_httpRequestArray);
    [super dealloc];
}

-(NSMutableArray *)httpRequestArray
{
    if (!_httpRequestArray) {
        _httpRequestArray = [[NSMutableArray alloc] init];
    }
    return _httpRequestArray;
}
-(void)downloadImageWithURL:(NSString *)urlString userInfo:(id)userInfo
{
    ASIHTTPRequest * request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:urlString]];
    request.userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
                        urlString,IMAGE_DOWNLOADER_URL_STRING,
                        userInfo,IMAGE_DOWNLOADER_USERINFO,
                        nil];
    [request setDelegate:self];
    [request setDidFinishSelector:@selector(requestDidFinish:)];
    [request setDidFailSelector:@selector(requestFaild:)];
    [request startAsynchronous];
    [self.httpRequestArray addObject:request];
}
-(void)requestFaild:(ASIHTTPRequest *)request
{
    ITTDINFO(@"image download faild");
}
-(void)requestDidFinish:(ASIHTTPRequest *)request
{
    
    id userInfo = [request.userInfo objectForKey:IMAGE_DOWNLOADER_USERINFO];
    ITTDINFO(@"第%d张下载完成",[userInfo intValue]);
    UIImage * image = [UIImage imageWithData:[request responseData]];
    if ([self.delegate respondsToSelector:(@selector(imageDownLoaderAtUserInfo:image:))]) {
        [self.delegate imageDownLoaderAtUserInfo:userInfo image:image];
    }
}

@end

